//
//  FaceSwithView.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/8/2.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit

enum faceStyle: Int {
    //最近
    case recent = 10
    //默认
    case normal = 11
    //emoji
    case emoji = 12
    //浪小花
    case lxh = 13
    
}


class FaceSwithView: UIStackView {
    
    var clickFaceSwithButtonClusure: ((faceStyle)->())?
    
    var priviousButton: UIButton?
    
    var firstBUtton: UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //MARK: - 界面设置
    func setupUI(){
        //平铺方向
        self.axis = .horizontal
        //填充
        self.distribution = .fillEqually
        
        addButton(title: "最近", backgroudImageName: "compose_emotion_table_left", type: .recent)
        firstBUtton = addButton(title: "默认", backgroudImageName: "compose_emotion_table_mid", type: .normal)
        addButton(title: "emoji", backgroudImageName: "compose_emotion_table_mid", type: .emoji)
        addButton(title: "浪小花", backgroudImageName: "compose_emotion_table_right", type: .lxh)
        
    }
    
    
    
    
    
    
    //MARK: - 按钮封装
    @discardableResult
    func addButton(title: String,backgroudImageName: String,type: faceStyle)->UIButton{
        let button = UIButton()
        
        button.tag = type.rawValue
        
        button.addTarget(self, action: #selector(clickButton(button:)), for: .touchUpInside)
        
        button.setTitle(title, for: .normal)
        
        button.setBackgroundImage(UIImage(named: "\(backgroudImageName)_normal"), for: .normal)
        button.setBackgroundImage(UIImage(named: "\(backgroudImageName)_selected"), for: .selected)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        
        addArrangedSubview(button)
        
        //关闭按钮的点击高亮
        button.adjustsImageWhenHighlighted = false
        
        return button
    }
    
    //MARK: - 按钮点击方法
    func clickButton(button: UIButton){
        
        if button == priviousButton{
            return
        }
        
        priviousButton?.isSelected = false
        
        button.isSelected = true
        
        priviousButton = button
        
        let type = faceStyle(rawValue: button.tag)
        
        clickFaceSwithButtonClusure?(type!)
        
    }
    
    //MARK: - 滑动表情后的按钮被选中
    func selectButton(indexPath: IndexPath) {
        
        let button = viewWithTag(indexPath.section + 10) as! UIButton
        
        if button == priviousButton{
            return
        }
        
        priviousButton?.isSelected = false
        
        button.isSelected = true
        
        priviousButton = button
    }
    
    //在这里为选中初始按钮
    override func layoutSubviews() {
        super.layoutSubviews()
        
        clickButton(button: firstBUtton!)
    }

}
